Lab 1: Intro to R and data analysis

…. more details

M. Chiara Mimmi, Ph.D. | Università degli Studi di Pavia

July 25, 2024

Lecture 1: topics illustrated in class

  • Introduction to R and R-studio
    • Why R?
    • Principles of reproducible analysis with R + RStudio
  • R objects, functions, packages
  • Understanding different types of variables
    • Principles of “tidy data”
  • Descriptive statistics
    • Measures of central tendency, measures of variability (or spread), and frequency distribution
  • Visual data exploration
    • {ggplot2}
  • Foundations of inference

INTRO TO R AND RSTUDIO

R version

If you have previously installed R on your machine, you can check which version you are running by executing this command in R:

# check your R version
R.Version()
$platform
[1] "x86_64-apple-darwin17.0"

$arch
[1] "x86_64"

$os
[1] "darwin17.0"

$system
[1] "x86_64, darwin17.0"

$status
[1] ""

$major
[1] "4"

$minor
[1] "2.2"

$year
[1] "2022"

$month
[1] "10"

$day
[1] "31"

$`svn rev`
[1] "83211"

$language
[1] "R"

$version.string
[1] "R version 4.2.2 (2022-10-31)"

$nickname
[1] "Innocent and Trusting"
# or just
#R.version.string

Install

R is available for free for Windows , GNU/Linux , and macOS .

  • To install R, you can go to this https://cloud.r-project.org/. The latest available release is R 4.3.3 “Angel Food Cake” released on 2024-02/29, but any (fairly recent) version will do.

Install RStudio IDE

RStudio Desktop is an Integrated Development Editor (IDE), basically a graphical interface wrapping and interfacing R (which needs to be installed first).

Besides RStudio, R (which is a command line driven program) can be executed:

  • via its native interface (R GUI)

  • from many other code editors, like VS Code, Sublime Text, Jupyter Notebook

  • To install RStudio you can go to this https://posit.co/download/rstudio-desktop/. The free-version contains everything you need.

Use RStudio IDE

RStudio Pane Layout Source: Posit’s RStudio User Guide

Creating an R Project [in Rstudio]

An R Project will keep all the files associated with a project (including invisible ones!) organized together – input data, R scripts, analytical results, figures. Besides being common practice, this has the advantage of implicitly setting the “working directory”, which is incredibly important when you need to load or output files, specifying their file path.

In Figure 1 you can see how easy it is just following RStudio prompts:

  • Create a new directory for each project
  • Select parent folder

Creating an R Project [in Rstudio] (cont.)

Figure 1: Creating an R project

Install R packages from CRAN (stable version)

An R package* is a shareable bundle of functions. Besides the basic built-in functions already contained in the program (i.e. the base package), many useful R functions come in free libraries of code (or packages) written by R’s users. You can find them in different repositories:

To install a package use utils function install.packages("package_name)

# Installing (ONLY the 1st time)
utils::install.packages('here')

# OR (same)
install.packages('here')

Install R packages from GitHub (testing version)

With the package devtools and its function install_github to install the developer’s version of a package. Let’s try it with a little package paint (which colors the structure of dataset when printing).

# Installing devtools (ONLY the 1st time)
utils::install.packages('devtools')

# Installing paint from GitHub 
library(devtools)
devtools::install_github("MilesMcBain/paint")

# test paint out
library(paint)
# ... instead of plain old 
print(str(mtcars))
'data.frame':   32 obs. of  11 variables:
 $ mpg : num  21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
 $ cyl : num  6 6 4 6 8 6 8 4 4 6 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...
NULL
# it will show me the structure of a data.frame like this... 
paint::paint(mtcars)

Install R packages RStudio pane

You can also install and update packages using the “Packages” tab on the lower right pane of RStudio.

Screenshot Install/Update pckgs from RStudio

Use R Packages

  • We will be using {base} & {utils} (pre-installed and pre-loaded)
  • We will also use the packages below (specifying package::function for clarity).
# Load them for this R session
library(here)      # tools find your project's files, based on working directory
library(janitor)   # tools for examining and cleaning data
library(skimr)     # tools for summary statistics 
library(dplyr)     # {tidyverse} tools for manipulating and summarising tidy data 
library(ggplot2)   # {tidyverse} tools for plotting
library(forcats)   # {tidyverse} tool for handling factors
library(ggridges)  # alternative to plot density functions 
library(fs)        # file/directory interactions

Help on R package/function

To inquire about a package and/or its functions, you can again write in your console ?package_name or ??package_name and RStudio will open up the Help page in the lower right pane.

# Opening Help page on package/function
?here

??here

File paths logistics

It is never good practice to “hard code” the file’s absolute path: most likely it will break your code as soon as you (or someone else) need to run it on a different computer, let alone within a different OS.

So if your code to read & load a file is written like this:

# [NOT REPRODUCIBLE] hard coding your file path  -----------------------

# File path on Mac:
dataset <- readr::read_csv(
  "/Users/testuser/R4biostats/input_data/dataset.csv")
# Same file path on Windows:
dataset <- readr::read_csv(
  "C:\Users\testuser\R4biostats\input_data\dataset.csv")

…it won’t work on someone else’s computer since they don’t have that same file structure!

(Reproducible) file paths with here [in Rstudio]

The here package lets you reference file paths in a reproducible manner (anchored on the R Project’s folder as the root).

Where is my Working Directory?

here::here()

You should get “/Users/dir/sub_dir/proj_name”

Create a Sub-Directory with fs package (for saving input data and output data)

# with `here` I simply add subfolder names relative to my wd 
fs::dir_create(here("practice", "test","data_input"))
# ...and a subfolder to put output files at the end
fs::dir_create(here("practice", "test","data_output"))

## --- [if I need to remove it (I have them already)]
fs::dir_delete(here("practice", "test"))

R OBJECTS, FUNCTIONS, PACKAGES

Importing data into R workspace

We are using real data provided by Thabtah,Fadi. (2017). Autism Screening Adult. UCI Machine Learning Repository. https://doi.org/10.24432/C5F019

We use utils::read.csv to load a csv file

?read.csv # to learn about function and arguments 

Option 1: from a url

  • head extract the first 6 rows
autism_data_url <- read.csv(
  file = "https://raw.githubusercontent.com/Sydney-Informatics-Hub/lessonbmc/gh-pages/_episodes_rmd/data/autism_data.csv", 
  header = TRUE, # 1st line is the name of the variables
  sep = ",", # which is the field separator character.
  na.strings = c("?") # specific values R should interpret as NA
)

Option 2: from my folder (upon downloading)

# Check my working directory location
# here::here()

# Use `here` in specifying all the subfolders AFTER the working directory 
autism_data_file <- read.csv(
  file = here("practice", "data_input", "01_datasets", "autism_data.csv"), 
  header = TRUE, # 1st line is the name of the variables
  sep = ",", # which is the field separator character.
  na.strings = c("?"),# specific values R should interpret as NA
  row.names = NULL) 

DATA OBSERVATION & MANIPULATION

Viewing the dataset

View(autism_data_file)  # (or click on it in Enviroment tab)
# What data type is this data?
class(autism_data_file)
[1] "data.frame"
# What variables are included in this dataset?
base::colnames(autism_data_file)
 [1] "id"              "A1_Score"        "A2_Score"        "A3_Score"       
 [5] "A4_Score"        "A5_Score"        "A6_Score"        "A7_Score"       
 [9] "A8_Score"        "A9_Score"        "A10_Score"       "age"            
[13] "gender"          "ethnicity"       "jaundice"        "autism"         
[17] "contry_of_res"   "used_app_before" "result"          "age_desc"       
[21] "relation"        "Class.ASD"      

Manipulate / clean the dataframe

I want a more consistent naming (no “.”, only “_”), so I use a very handy function clean_names from the {janitor} package

autism_data <- janitor::clean_names(autism_data_file, 
                                     case = "none") 
# check change
colnames(autism_data)
 [1] "id"              "A1_Score"        "A2_Score"        "A3_Score"       
 [5] "A4_Score"        "A5_Score"        "A6_Score"        "A7_Score"       
 [9] "A8_Score"        "A9_Score"        "A10_Score"       "age"            
[13] "gender"          "ethnicity"       "jaundice"        "autism"         
[17] "contry_of_res"   "used_app_before" "result"          "age_desc"       
[21] "relation"        "Class_ASD"      
dim(autism_data)
[1] 704  22
  • The option case = "none" leaves the case as is, but only uses “_” separator (you can also use it with no arguments )

Isolate a variable (column)

# With the `$` sign I extract a variable (column name)
autism_data$id
  [1]   1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18
 [19]  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36
 [37]  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54
 [55]  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72
 [73]  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90
 [91]  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108
[109] 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
[127] 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
[145] 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
[163] 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
[181] 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
[199] 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
[217] 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
[235] 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
[253] 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
[271] 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
[289] 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
[307] 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
[325] 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
[343] 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
[361] 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
[379] 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
[397] 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
[415] 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
[433] 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
[451] 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
[469] 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
[487] 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
[505] 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
[523] 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
[541] 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
[559] 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
[577] 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594
[595] 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612
[613] 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
[631] 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
[649] 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
[667] 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
[685] 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
[703] 703 704
autism_data$A1_Score
  [1] 1 1 1 1 1 1 0 1 1 1 1 0 0 1 1 1 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 1 1 1 0 0
 [38] 1 1 1 1 0 0 0 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 1 0 1 0 1 1
 [75] 0 1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 0 0 1 1 1 0 0 0 1 1 1 1
[112] 0 1 0 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 0 1 0 0 1 0 0 1 1 1 0 1 1 1
[149] 1 1 0 0 1 0 1 0 1 0 1 1 0 0 0 1 1 1 0 1 0 1 1 1 0 1 1 1 1 0 1 1 1 1 0 0 0
[186] 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0
[223] 1 1 1 0 1 0 0 1 1 1 1 0 0 1 1 1 0 1 1 1 1 0 1 1 1 0 0 1 1 1 0 0 1 1 1 0 1
[260] 1 0 1 1 0 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 0 1 1 0 1 0 0 0 1 0 1 1 1 0 1 0 1
[297] 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 0 1 1 1 1 0 0 1 0 1 0 1 1 1 1 1 0 1 0 1 1 1
[334] 1 1 1 1 1 1 1 1 1 1 1 0 1 1 0 1 1 1 1 0 1 0 0 1 1 1 0 1 0 0 0 0 1 1 0 1 0
[371] 1 1 0 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 0 1 1 0 1 1 0 1 0 0 1 1 1 1 1 0 1 0
[408] 1 1 1 1 0 0 0 1 1 1 1 1 1 1 0 1 0 1 1 1 1 0 1 1 1 1 1 1 0 1 1 1 0 1 1 0 1
[445] 0 1 1 1 1 1 1 0 1 0 1 1 1 0 0 1 0 0 0 0 1 1 0 1 1 0 0 1 1 1 1 1 0 1 1 0 1
[482] 0 0 1 1 0 1 1 0 1 1 0 1 1 1 1 0 0 1 1 0 1 0 1 1 1 1 0 1 0 0 1 1 1 1 1 1 1
[519] 0 0 1 1 1 1 1 1 0 0 1 0 1 1 0 0 0 0 0 0 1 0 1 0 0 0 1 1 1 0 1 1 1 1 0 1 1
[556] 1 1 1 1 0 1 1 0 1 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 0 0
[593] 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 0 1 1 1 1 1 1 0 0 1 0 1 1 1 1 1 1 1 1
[630] 1 1 0 0 1 1 0 0 1 1 1 1 1 0 1 1 1 1 1 1 0 1 1 0 1 1 1 1 1 0 1 1 1 1 1 0 1
[667] 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 0 1 1 1
[704] 1

Add a new column

I prefer to rename the dataframe when I make changes

# rename dataframe 
autism_pids <- autism_data
# create a new column 
autism_pids$pids <- paste("PatientID_" , autism_data$id, sep = "")
base::colnames(autism_pids)
 [1] "id"              "A1_Score"        "A2_Score"        "A3_Score"       
 [5] "A4_Score"        "A5_Score"        "A6_Score"        "A7_Score"       
 [9] "A8_Score"        "A9_Score"        "A10_Score"       "age"            
[13] "gender"          "ethnicity"       "jaundice"        "autism"         
[17] "contry_of_res"   "used_app_before" "result"          "age_desc"       
[21] "relation"        "Class_ASD"       "pids"           
# check change in df structure
dim(autism_data)
[1] 704  22
dim(autism_pids)
[1] 704  23

(optional) Clean up my workspace1

# what do I have in the environment? 
ls() 
[1] "autism_data"      "autism_data_file" "autism_pids"     
# remove all EXCEPT for "autism_pids" 
rm("autism_data", "autism_data_file", "autism_data_url" ) 


Different ways to select rows &/or columns

Option 1 using the $ sign from base

# With the `$` sign I extract a variable (column name)
head(autism_pids$id) 
[1] 1 2 3 4 5 6
head(autism_pids$pids)
[1] "PatientID_1" "PatientID_2" "PatientID_3" "PatientID_4" "PatientID_5"
[6] "PatientID_6"
head(autism_pids$A1_Score)
[1] 1 1 1 1 1 1
head(autism_pids$ethnicity)
[1] "White-European" "Latino"         "Latino"         "White-European"
[5] NA               "Others"        

Option 2 using indexing [ , #col] from base

# Indexing to pick `[ , #col]`  
head(autism_pids[ ,1] )# empty rows means all 
[1] 1 2 3 4 5 6
head(autism_pids[ ,23])
[1] "PatientID_1" "PatientID_2" "PatientID_3" "PatientID_4" "PatientID_5"
[6] "PatientID_6"
head(autism_pids[ ,2])
[1] 1 1 1 1 1 1
head(autism_pids[ ,14])
[1] "White-European" "Latino"         "Latino"         "White-European"
[5] NA               "Others"        

Option 2 using indexing [#row, ] from base

# Indexing to pick `[#row, ]`  
head(autism_pids[1 , ] ) # empty cols means all 
  id A1_Score A2_Score A3_Score A4_Score A5_Score A6_Score A7_Score A8_Score
1  1        1        1        1        1        0        0        1        1
  A9_Score A10_Score age gender      ethnicity jaundice autism contry_of_res
1        0         0  26      f White-European       no     no United States
  used_app_before result    age_desc relation Class_ASD        pids
1              no      6 18 and more     Self        NO PatientID_1
head(autism_pids[50,])
   id A1_Score A2_Score A3_Score A4_Score A5_Score A6_Score A7_Score A8_Score
50 50        1        1        0        0        0        1        1        1
   A9_Score A10_Score age gender ethnicity jaundice autism contry_of_res
50        0         1  30      f     Asian       no     no    Bangladesh
   used_app_before result    age_desc relation Class_ASD         pids
50              no      6 18 and more     Self        NO PatientID_50
head(autism_pids[25:26 ,])
   id A1_Score A2_Score A3_Score A4_Score A5_Score A6_Score A7_Score A8_Score
25 25        1        1        1        1        0        0        0        1
26 26        0        1        1        0        0        0        0        1
   A9_Score A10_Score age gender ethnicity jaundice autism contry_of_res
25        0         0  43      m      <NA>       no     no       Lebanon
26        0         0  24      f      <NA>      yes     no   Afghanistan
   used_app_before result    age_desc relation Class_ASD         pids
25              no      5 18 and more     <NA>        NO PatientID_25
26              no      3 18 and more     <NA>        NO PatientID_26

Option 2 using indexing [#row, #col] from base

# Indexing to pick `[#row, #col]`  
autism_pids[1:3,1]
[1] 1 2 3
autism_pids[1:3,23]
[1] "PatientID_1" "PatientID_2" "PatientID_3"
autism_pids[1:3,2]
[1] 1 1 1
autism_pids[1:3,14]
[1] "White-European" "Latino"         "Latino"        

What are the data types of the variables?

Option 1 using base functions

# What are the data types of the variables? ---------------------------------
str(autism_pids) # integer and character
'data.frame':   704 obs. of  23 variables:
 $ id             : int  1 2 3 4 5 6 7 8 9 10 ...
 $ A1_Score       : int  1 1 1 1 1 1 0 1 1 1 ...
 $ A2_Score       : int  1 1 1 1 0 1 1 1 1 1 ...
 $ A3_Score       : int  1 0 0 0 0 1 0 1 0 1 ...
 $ A4_Score       : int  1 1 1 1 0 1 0 1 0 1 ...
 $ A5_Score       : int  0 0 1 0 0 1 0 0 1 0 ...
 $ A6_Score       : int  0 0 0 0 0 0 0 0 0 1 ...
 $ A7_Score       : int  1 0 1 1 0 1 0 0 0 1 ...
 $ A8_Score       : int  1 1 1 1 1 1 1 0 1 1 ...
 $ A9_Score       : int  0 0 1 0 0 1 0 1 1 1 ...
 $ A10_Score      : int  0 1 1 1 0 1 0 0 1 0 ...
 $ age            : int  26 24 27 35 40 36 17 64 29 17 ...
 $ gender         : chr  "f" "m" "m" "f" ...
 $ ethnicity      : chr  "White-European" "Latino" "Latino" "White-European" ...
 $ jaundice       : chr  "no" "no" "yes" "no" ...
 $ autism         : chr  "no" "yes" "yes" "yes" ...
 $ contry_of_res  : chr  "United States" "Brazil" "Spain" "United States" ...
 $ used_app_before: chr  "no" "no" "no" "no" ...
 $ result         : int  6 5 8 6 2 9 2 5 6 8 ...
 $ age_desc       : chr  "18 and more" "18 and more" "18 and more" "18 and more" ...
 $ relation       : chr  "Self" "Self" "Parent" "Self" ...
 $ Class_ASD      : chr  "NO" "NO" "YES" "NO" ...
 $ pids           : chr  "PatientID_1" "PatientID_2" "PatientID_3" "PatientID_4" ...

Option 1 using base functions (cont.)

# What values can the variables take? ---------------------------------
summary(autism_pids$pids)
   Length     Class      Mode 
      704 character character 
length(unique(autism_pids$pids)) # N unique values
[1] 704
sum(is.na(autism_pids$pids)) # N missing values
[1] 0
summary(autism_pids$ethnicity)
   Length     Class      Mode 
      704 character character 
length(unique(autism_pids$ethnicity)) # N unique values
[1] 12
sum(is.na(autism_pids$ethnicity)) # N missing values
[1] 95

Option 2 using {skimr} function skim

autism_pids %>% 
  skimr::skim(pids) %>%
  dplyr::select(#skim_variable, 
                skim_type, 
                complete_rate,
                n_missing, 
                character.n_unique)
# A tibble: 1 × 4
  skim_type complete_rate n_missing character.n_unique
  <chr>             <dbl>     <int>              <int>
1 character             1         0                704

Option 2 using {skimr} function skim (cont.)

autism_pids %>% 
  skimr::skim(ethnicity) %>%
  dplyr::select(#skim_variable, 
                skim_type, 
                complete_rate,
                n_missing, 
                character.n_unique)
# A tibble: 1 × 4
  skim_type complete_rate n_missing character.n_unique
  <chr>             <dbl>     <int>              <int>
1 character         0.865        95                 11

Option 2 using {skimr} function skim (cont.)

# I can use it for the WHOLE dataframe!
autism_pids %>% 
  skimr::skim()

Recoding some variables

from char to factor

#### char 2 factor -------------------------------------------------------------
# Say I want to treat some variables as factors
autism_pids$gender <- as.factor(autism_pids$gender)
autism_pids$ethnicity <- as.factor(autism_pids$ethnicity)
autism_pids$contry_of_res <- as.factor(autism_pids$contry_of_res)
autism_pids$relation <- as.factor(autism_pids$relation)

 
# check 
class(autism_pids$gender)
[1] "factor"
class(autism_pids$ethnicity)
[1] "factor"
class(autism_pids$contry_of_res)
[1] "factor"
class(autism_pids$relation)
[1] "factor"
# now I have Variable type: factor
autism_pids_temp <- autism_pids # copy df for test 

to_factor <- c("gender", "ethnicity", "contry_of_res", "relation") # vector of col names 
autism_pids_temp[ ,to_factor] <-  lapply(X =  autism_pids[ ,to_factor], FUN = as.factor)

# check 
class(autism_pids_temp$gender)
[1] "factor"
class(autism_pids_temp$ethnicity)
[1] "factor"
class(autism_pids_temp$contry_of_res)
[1] "factor"
class(autism_pids_temp$relation)
[1] "factor"
# now I have Variable type: factor

Inspect factors levels (3 different ways)

  • using {base} levels functions
levels(autism_pids$ethnicity)
 [1] "Asian"           "Black"           "Hispanic"        "Latino"         
 [5] "Middle Eastern " "others"          "Others"          "Pasifika"       
 [9] "South Asian"     "Turkish"         "White-European" 
  • using {base} table functions
table(autism_pids$ethnicity,useNA = "ifany")

          Asian           Black        Hispanic          Latino Middle Eastern  
            123              43              13              20              92 
         others          Others        Pasifika     South Asian         Turkish 
              1              30              12              36               6 
 White-European            <NA> 
            233              95 

Inspect factors levels – 3 different ways (cont.)

  • using {janitor} function tabyl, which uses the “pipe” operator %>% which takes the output of a function as input of the next one
janitor::tabyl(autism_pids$ethnicity) %>% 
  adorn_totals() %>% 
  adorn_pct_formatting()
 autism_pids$ethnicity   n percent valid_percent
                 Asian 123   17.5%         20.2%
                 Black  43    6.1%          7.1%
              Hispanic  13    1.8%          2.1%
                Latino  20    2.8%          3.3%
       Middle Eastern   92   13.1%         15.1%
                others   1    0.1%          0.2%
                Others  30    4.3%          4.9%
              Pasifika  12    1.7%          2.0%
           South Asian  36    5.1%          5.9%
               Turkish   6    0.9%          1.0%
        White-European 233   33.1%         38.3%
                  <NA>  95   13.5%             -
                 Total 704  100.0%        100.0%

Inspect factors levels – 3 different ways (cont.)

  • check if the 95 missing obs are the same missing for ethnicity and relation
which(is.na(autism_pids$ethnicity)) # indices of TRUE elements in vector
 [1]   5  13  14  15  20  21  25  26  63  80  81  82  92 217 222 239 258 271 277
[20] 278 286 307 316 325 338 339 340 341 342 343 344 345 346 347 348 349 350 351
[39] 352 353 354 355 356 362 366 370 371 373 379 380 381 382 383 384 385 386 387
[58] 388 389 391 396 400 401 402 404 424 428 429 430 433 439 454 486 506 519 528
[77] 535 536 537 538 557 565 572 573 589 594 637 643 646 652 653 659 660 667 702
which(is.na(autism_pids$relation))  # indices of TRUE elements in vector
 [1]   5  13  14  15  20  21  25  26  63  80  81  82  92 217 222 239 258 271 277
[20] 278 286 307 316 325 338 339 340 341 342 343 344 345 346 347 348 349 350 351
[39] 352 353 354 355 356 362 366 370 371 373 379 380 381 382 383 384 385 386 387
[58] 388 389 391 396 400 401 402 404 424 428 429 430 433 439 454 486 506 519 528
[77] 535 536 537 538 557 565 572 573 589 594 637 643 646 652 653 659 660 667 702

…indeed they are!

from char to logical

# observe a subset of some columns 
autism_subset <- autism_pids [1:5, c("gender","jaundice", "autism", "age_desc", "Class_ASD","pids")]
# View(autism_subset)

# recode "age_desc" as LOGICAL new var "age_desc_log"
autism_pids$age_desc_log <- ifelse(autism_pids$age_desc == "18 and more", TRUE, FALSE )
class(autism_pids$age_desc)
[1] "character"
class(autism_pids$age_desc_log)
[1] "logical"

from char to dummy [0,1]

I also may need my binary variables expressed as 01 (e.g. to incorporate nominal variables into regression analysis)

autism_pids$autism_dummy <- ifelse(autism_pids$autism == 'yes', 1, 0)
class(autism_pids$autism)
[1] "character"
class(autism_pids$autism_dummy)
[1] "numeric"

Subsetting the data for further investigation

Recall how to view the names of columns / variables

colnames(autism_pids)
 [1] "id"              "A1_Score"        "A2_Score"        "A3_Score"       
 [5] "A4_Score"        "A5_Score"        "A6_Score"        "A7_Score"       
 [9] "A8_Score"        "A9_Score"        "A10_Score"       "age"            
[13] "gender"          "ethnicity"       "jaundice"        "autism"         
[17] "contry_of_res"   "used_app_before" "result"          "age_desc"       
[21] "relation"        "Class_ASD"       "pids"            "age_desc_log"   
[25] "autism_dummy"   

using {utils} head or tail

head(autism_pids)   #return fist 6 obs
tail(autism_pids)   #return last 6 obs

using {utils} head or tail (cont.)

head(autism_pids, n = 2) #return fist 2 obs
  id A1_Score A2_Score A3_Score A4_Score A5_Score A6_Score A7_Score A8_Score
1  1        1        1        1        1        0        0        1        1
2  2        1        1        0        1        0        0        0        1
  A9_Score A10_Score age gender      ethnicity jaundice autism contry_of_res
1        0         0  26      f White-European       no     no United States
2        0         1  24      m         Latino       no    yes        Brazil
  used_app_before result    age_desc relation Class_ASD        pids
1              no      6 18 and more     Self        NO PatientID_1
2              no      5 18 and more     Self        NO PatientID_2
  age_desc_log autism_dummy
1         TRUE            0
2         TRUE            1
tail(autism_pids, n = 2) #return last 2 obs
     id A1_Score A2_Score A3_Score A4_Score A5_Score A6_Score A7_Score A8_Score
703 703        1        0        0        1        1        0        1        0
704 704        1        0        1        1        1        0        1        1
    A9_Score A10_Score age gender      ethnicity jaundice autism contry_of_res
703        1         1  35      m    South Asian       no     no      Pakistan
704        1         1  26      f White-European       no     no        Cyprus
    used_app_before result    age_desc relation Class_ASD          pids
703              no      6 18 and more     Self        NO PatientID_703
704              no      8 18 and more     Self       YES PatientID_704
    age_desc_log autism_dummy
703         TRUE            0
704         TRUE            0

Investigating a subset of observations

E.g. I learned that some patients have missing age… how many are they?

# run...
sum(is.na(autism_pids$age)) 
[1] 2
# or 
skimr::n_missing(autism_pids$age)
[1] 2

Next, I want to ID those patients with missing age

New df (only the patients with missing age) as SUBSET of the given df

I want to extract only the obs (rows) of interest with a few useful vars (cols)

missing_age_subset <- autism_pids[is.na(autism_pids$age), c("pids", "age", "autism_dummy") ]
missing_age_subset
           pids age autism_dummy
63 PatientID_63  NA            0
92 PatientID_92  NA            0
missing_age_subset3 <- autism_pids[which(is.na(autism_pids$age)), c("pids", "age", "autism_dummy")] 
missing_age_subset3
           pids age autism_dummy
63 PatientID_63  NA            0
92 PatientID_92  NA            0

Subset using subset from base

# arguments allow me to specify rows and cols 
missing_age_subset2 <- subset(x = autism_pids, 
                              subset = is.na(autism_pids$age), # 1 logical condition
                              select = c("pids", "age", "autism_dummy") # which cols
                              ) 
missing_age_subset2
           pids age autism_dummy
63 PatientID_63  NA            0
92 PatientID_92  NA            0
# Creates a SUBSET based on MORE conditions (`age` and `ethnicity`)
subset_2cond <- subset(x = autism_pids, 
                       # 2 logical conditions      
                       subset = age < 50 & contry_of_res == "Brazil", 
                       # pick a few cols 
                       select = c("pids", "age", "contry_of_res",
                                  "autism_dummy")
) 

subset_2cond
             pids age contry_of_res autism_dummy
2     PatientID_2  24        Brazil            1
54   PatientID_54  21        Brazil            1
94   PatientID_94  19        Brazil            1
169 PatientID_169  36        Brazil            1
170 PatientID_170  36        Brazil            1
429 PatientID_429  20        Brazil            0
587 PatientID_587  21        Brazil            0
588 PatientID_588  21        Brazil            0
696 PatientID_696  28        Brazil            0

Subset using {dplyr} filter and select

Switching to the package dplyr and embracing the “pipe” (%>%) operator logic, in which the filtering (rows) and selecting (columns) is done in sequence

## here the filtering (rows) and selecting (columns) is done in sequence
twocond_dplyr_subset <- autism_pids %>% 
  dplyr::filter(age < 50 & contry_of_res == "Brazil") %>%  # which rows
  dplyr::select (pids, age, contry_of_res, autism_dummy)   # which cols

twocond_dplyr_subset
           pids age contry_of_res autism_dummy
1   PatientID_2  24        Brazil            1
2  PatientID_54  21        Brazil            1
3  PatientID_94  19        Brazil            1
4 PatientID_169  36        Brazil            1
5 PatientID_170  36        Brazil            1
6 PatientID_429  20        Brazil            0
7 PatientID_587  21        Brazil            0
8 PatientID_588  21        Brazil            0
9 PatientID_696  28        Brazil            0

Dealing with missing data

Input values where missing

⚠︎ WARNING ⚠︎ This is a very delicate step, because any data that is modified or imputed beyond the original collection can affect the result of subsequent analysis and statistical modeling.

Furthermore, it will be necessary to document and justify whichever approach is used to deal with missing data.

# 1/2 create a new variable 
autism_pids$age_inputed <- autism_pids$age
# 2/2 replace value (presumably taken from other source) of `aged_inputed` 
  # CONDITIONAL on `pids`
autism_pids$age_inputed[autism_pids$pids == "PatientID_63"] <-  65
autism_pids$age_inputed[autism_pids$pids == "PatientID_92"] <-  75

# check
skimr::n_missing(autism_pids$age) 
[1] 2
skimr::n_missing(autism_pids$age_inputed)  
[1] 0

DESCRIPTIVE STATISTICS

Summarizing all variables

{base} summary

summary(autism_pids)

{skimr} skim

skimr::skim(autism_pids)

Notice the different treatment according to the variable type

The function’s results depend on the class of the object

  • integer (A1_Score)
summary(autism_pids$A1_Score)     # min, max quartiles, mean, median
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
 0.0000  0.0000  1.0000  0.7216  1.0000  1.0000 
  • factor (ethnicity)
summary(autism_pids$ethnicity)    # counts of levels' frequency (included NA!)
          Asian           Black        Hispanic          Latino Middle Eastern  
            123              43              13              20              92 
         others          Others        Pasifika     South Asian         Turkish 
              1              30              12              36               6 
 White-European            NA's 
            233              95 

Notice the different treatment according to the variable type

  • logical (age_desc_log)
summary(autism_pids$age_desc_log) # counts of TRUE 
   Mode    TRUE 
logical     704 

Frequency tables

  • Frequency distributions can be used for nominal, ordinal, or interval/ration variables
table(autism_pids$gender)

  f   m 
337 367 
table(autism_pids$age) # automatically drops missing...

17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 
18 31 35 46 49 37 37 34 27 28 31 24 27 30 21 18 16 12 17 13 17 13  7 16  3 15 
43 44 45 46 47 48 49 50 51 52 53 54 55 56 58 59 60 61 64 
11 10  4  6  8  4  3  5  1  5  6  2  6  2  2  1  1  2  1 
table(autism_pids$age, useNA = "ifany") #...unless specified

  17   18   19   20   21   22   23   24   25   26   27   28   29   30   31   32 
  18   31   35   46   49   37   37   34   27   28   31   24   27   30   21   18 
  33   34   35   36   37   38   39   40   41   42   43   44   45   46   47   48 
  16   12   17   13   17   13    7   16    3   15   11   10    4    6    8    4 
  49   50   51   52   53   54   55   56   58   59   60   61   64 <NA> 
   3    5    1    5    6    2    6    2    2    1    1    2    1    2 

Cross tabulation

  • Cross tabulation
table(autism_pids$gender, autism_pids$age_inputed)
   
    17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
  f  7 11 22 22 18 14 17 10 11 14 18 15 16 13  8 14  6  7 12  7 11  6  5  9  0
  m 11 20 13 24 31 23 20 24 16 14 13  9 11 17 13  4 10  5  5  6  6  7  2  7  3
   
    42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 58 59 60 61 64 65 75
  f  6  5  4  4  4  3  2  2  2  0  2  4  1  1  0  1  0  1  1  0  0  1
  m  9  6  6  0  2  5  2  1  3  1  3  2  1  5  2  1  1  0  1  1  1  0
table(autism_pids$ethnicity, autism_pids$autism_dummy)
                 
                    0   1
  Asian           118   5
  Black            38   5
  Hispanic         12   1
  Latino           12   8
  Middle Eastern   83   9
  others            1   0
  Others           28   2
  Pasifika         10   2
  South Asian      34   2
  Turkish           5   1
  White-European  183  50

Grouping and summarizing with {base}

E.g. I want to know the average age of men and women

Here are 3 ways using `base R

# by(data$column, data$grouping_column, mean)
by(data = autism_pids$age_inputed, INDICES = autism_pids$gender, FUN = mean)
autism_pids$gender: f
[1] 29.69139
------------------------------------------------------------ 
autism_pids$gender: m
[1] 28.98365
# i.e. apply a function to subsets of a vector or array, split by one or more factors.
tapply(X = autism_pids$age_inputed, INDEX = autism_pids$gender, FUN = mean)
       f        m 
29.69139 28.98365 
# sapply(split(data$column, data$grouping_column), mean)
sapply(X = split(autism_pids$age_inputed, autism_pids$gender),FUN = mean) # returns a vector
       f        m 
29.69139 28.98365 

Grouping and summarizing with {dplyr}

autism_pids %>% 
  dplyr::group_by(gender) %>% 
  dplyr::summarise(mean(age_inputed))  # returns a dataframe!
# A tibble: 2 × 2
  gender `mean(age_inputed)`
  <fct>                <dbl>
1 f                     29.7
2 m                     29.0

I could add more statistics to the grouped summary…

autism_pids %>% 
  dplyr::group_by(gender) %>% 
  dplyr::summarise(mean_age = mean(age_inputed),  
                   N_obs = n(), 
                   N_with_autism = sum(autism_dummy == 1)
  ) 
# A tibble: 2 × 4
  gender mean_age N_obs N_with_autism
  <fct>     <dbl> <int>         <int>
1 f          29.7   337            54
2 m          29.0   367            37

Measures of central tendency

Mean and median

Recall that

MEAN

Sample \(\mu=\frac{\sum_{i=1}^n x_{i}}n\) & Population \(\bar{x}=\frac{\sum_{i=1}^n x_{i}}n\)

MEDIAN

For uneven \(n\): \(\frac{x_{(n+1)}}2\) For even \(n\): \(\frac{x_{(n/2)} + x_{(n/2+1)}}2\)

Mean/Median using base

  • Important to specify the argument na.rm = TRUE or the function won’t work
## Let's use `age` and `age_inputed` to see what inputed missing values did 
mean(autism_pids$age)
[1] NA
median(autism_pids$age)
[1] NA
mean(autism_pids$age, na.rm = TRUE)
[1] 29.20655
median(autism_pids$age, na.rm = TRUE)
[1] 27
mean(autism_pids$age_inputed)
[1] 29.32244
median(autism_pids$age_inputed)
[1] 27

Create custom function to calculate statistical mode

R doesn’t have it so we need a custom function for the “mode”

f_calc_mode  <- function(x) { 
  # `unique` returns a vector of unique values 
  uni_x <- unique(x)  
  # `match` returns the index positions of 1st vector against 2nd vector
  match_x <- match(x, uni_x)
  # `tabulate` count the occurrences of integer values in a vector.
  tab_x  <-  tabulate(match_x) 
  # returns element of uni_x that corresponds to max occurrences
  uni_x[tab_x == max(tab_x)]
}
f_calc_mode(autism_pids$age)
[1] 21
f_calc_mode(autism_pids$age_inputed)
[1] 21

Measures of variability (or spread)

Variance and Standard deviation

Recall that

Variance Sample \(s^2 =\frac{\sum{(x_i-\bar{x})^2}}{n-1}\) & Population \(\sigma^2 = \frac{\displaystyle\sum_{i=1}^{n}(x_i - \mu)^2} {n}\)

Standard deviation Sample \(s = \sqrt\frac{\sum{(x_i-\bar{x})^2}}{n-1}\) & Population \(\sigma = \sqrt\frac{\displaystyle\sum_{i=1}^{n}(x_i - \mu)^2} {n}\)

var(autism_pids$age)
[1] NA
var(autism_pids$age_inputed)
[1] 98.81338
sd(autism_pids$age)
[1] NA
sd(autism_pids$age_inputed)
[1] 9.940492

VISUAL DATA EXPLORATION

Plotting with ggplot2

ggplot2 provides a set of tools to map data to visual elements on a plot, to specify the kind of plot you want, and then subsequently to control the fine details of how it will be displayed. It basically allows to build a plot layer by layer (Figure 2).

  • data -> specify what our dataset is
  • aesthetic mappings (or just aesthetics) -> specify which dataset’s variables will turn into the plot elements (e.g. \(x\) and \(y\) values, or categorical variable into colors, points, and shapes).
  • geom -> the overall type of plot, e.g. geom_point() makes scatterplots, geom_bar() makes barplots, geom_boxplot() makes boxplots.

Additional (optional) pieces:

  • information about the scales,
  • the labels of legends and axes
  • other guides that help people to read the plot,

Plotting with ggplot2 (cont.)

a layered approach!

Figure 2: ggplot2 layers Source: Andrew Heiss’ talk

Save some colors (for cutomizing plots)

two_col_palette <-  c("#9b2339", "#005ca1")
other_cols <- c("#E7B800","#239b85", "#85239b", "#9b8523","#23399b",
                "#d8e600", "#0084e6", "#399B23", "#e60066",
                "#00d8e6", "#e68000")

Distribution of continuous var

Histograms

Histograms (and density plots) are often used to show the distribution of a continuous variable.

ggplot(data = autism_pids, mapping = aes(x=age_inputed)) + 
  geom_histogram() + 
  theme_bw()

Histograms

… or (piped data)

# notice the  `%>%`  before using ggplot2...
autism_pids %>% 
  # then `+` when using ggplot2
  ggplot(aes(x = age_inputed )) + 
  geom_histogram() + 
  theme_bw()

… or (piped data)

… bin width

Histograms split the data into ranges (bins) and show the number of observations in each. Hence, it’s important to pick widths that represents the data well.

autism_pids %>% 
  ggplot(aes(x = age_inputed )) + 
  # specify to avoid warning if we fail to specify the number of bins 
  geom_histogram(bins=40) + 
  theme_bw()

… bin width

… mean vertical line

autism_pids %>% 
  ggplot(aes(x = age_inputed )) + 
  # specify to avoid warning if we fail to specify the number of bins 
  geom_histogram(bins=40) + 
  # add mean vertical line
  geom_vline(xintercept = mean(autism_pids$age_inputed),
             na.rm = FALSE,
             lwd=1,
             linetype=2,
             color="#9b2339") +
  # add small annotations (such as text labels) 
  annotate("text",                        
           # coordinates for positioning aesthetics on the graph
           x = mean(autism_pids$age_inputed) * 1.4,
           y = mean(autism_pids$age_inputed) * 1.7,
           label = paste("Mean =", round(mean(autism_pids$age_inputed), digits = 2)),
           col = "#9b2339",
           size = 4)+
theme_bw() 

… mean vertical line

Density plot

autism_pids %>% 
  ggplot(aes( x=age_inputed)) +
  geom_density()+
  theme_bw() 

Density plot

Density plot (cont.)

autism_pids %>% 
  ggplot(aes( x=age_inputed)) +
  geom_density(fill="#85239b", color="#e9ecef", alpha=0.5)+
  theme_bw() 

Density plot (cont.)

… increase # of x-axis ticks

autism_pids %>% 
  ggplot(aes( x=age_inputed)) +
  geom_density(fill="#85239b", color="#e9ecef", alpha=0.5)+
  theme_bw() + 
  # increase number of x axis ticks 
  scale_x_continuous(breaks = seq(10, 100,5 ), limits = c(16, 86))

… increase # of x-axis ticks

Distribution of continuous var split by categorical var

Histograms with fill = category

# specifying `fill` = gender
autism_pids %>% 
  ggplot(mapping = aes(x = age_inputed, fill = gender )) + 
  geom_histogram(bins=40) + 
  theme_bw()  

Histograms with fill = category

… shifting bars by group

# trying to improve readability 
autism_pids %>% 
  ggplot(mapping = aes(x = age_inputed, fill = gender )) + 
  # bars next to each other with `position = 'dodge'`
  geom_histogram(bins=40, position = 'dodge') + 
  theme_bw()

… shifting bars by group

…facet by gender

That’s still not very easy to digest. Instead of only filling, you can separate the data into multiple plots to improve readability

autism_pids %>% 
  ggplot(aes(x = age_inputed, fill = gender )) + 
  geom_histogram(color="#e9ecef", alpha=0.8, position = 'dodge') + 
  theme_bw() + 
  # splitting the gender groups, specifying `ncol` to see one above the other
  facet_wrap(~gender, ncol = 1)  + 
  scale_fill_cyclical(values = c("#9b2339","#005ca1"))

…facet by gender

… adding 2 mean vert lines (by gender)

I want to see the mean vertical line for each of the subgroups, but now, I need to create a small dataframae of summary statistics.

I do so by using dplyr add a column mean_age with the group mean

group_stats <- autism_pids %>% 
  dplyr::group_by(gender) %>% 
  dplyr::summarize(mean_age = mean(age_inputed),
                   median_age = median (age_inputed)) 

group_stats
# A tibble: 2 × 3
  gender mean_age median_age
  <fct>     <dbl>      <dbl>
1 f          29.7         28
2 m          29.0         26

…(Introducing tidyr::pivot_longer)

This is a case in which I need to reshape this small dataframe into long form. I do so using tidyr::pivot_longer function

My next plot will have two data sources

group_stats_long <- group_stats %>% 
  tidyr::pivot_longer(cols = mean_age:median_age, 
                      names_to = "Stat", 
                      values_to = "Value") %>% 
  dplyr::mutate(label = as.character(glue::glue("{gender}_{Stat}")))

group_stats_long 
# A tibble: 4 × 4
  gender Stat       Value label       
  <fct>  <chr>      <dbl> <chr>       
1 f      mean_age    29.7 f_mean_age  
2 f      median_age  28   f_median_age
3 m      mean_age    29.0 m_mean_age  
4 m      median_age  26   m_median_age

…facet by gender + 2 mean vert lines + scales

hist_plot <- autism_pids %>% 
  ggplot(aes(x = age_inputed, fill = gender)) + 
  geom_histogram(bins=30,color="#e9ecef", alpha=0.8, position = 'dodge') + 
  facet_wrap(~gender, ncol = 1 ) + 
  scale_fill_manual(values = c("#9b2339","#005ca1"))  +
  # adding vline 
  geom_vline(data = group_stats_long, 
             mapping = aes(xintercept = Value, color = Stat),
             lwd=1.5,
             linetype=6,
  ) + 
  labs(x = "age brackets", y = "n of individuals",
       color = "Stats",
       title = "Distribution of observations by gender",
       subtitle = "",
       caption = "Autism study") +
  theme_bw() + 
  theme(legend.position = "right",
        plot.title = element_text(face = "bold")) + 
  # increase number of x axis ticks 
  scale_color_manual(values = c( "#e68000", "#d8cf71")) +
  scale_x_continuous(breaks = seq(10, 100,10 ), limits = c(16, 86))

hist_plot

…facet by gender + 2 mean vert lines + scales

Density ggridges package

As an alternative, you can use the {ggridges} package to make ridge plots. The geom geom_density_ridges calculates density estimates from the provided data and then plots those, using the ridgeline visualization. In this case I have added the median line.

# library(ggridges)
autism_pids %>% 
  # this takes also `y` = group
  ggplot(aes(x=age_inputed, y = gender, fill = gender)) +
  ggridges::geom_density_ridges() +
  # I can add quantile lines (2 is the median)
  stat_density_ridges(quantile_lines = TRUE, quantiles = c(0.5), alpha = 0.75)+  
  # increase number of x axis ticks 
  scale_x_continuous(breaks = seq(10, 100,10 ), limits = c(16, 86)) + 
  scale_fill_cyclical(values = c("#9b2339","#005ca1")) + 
  theme_bw() 

Density ggridges package

Barchart

Bar charts provide a visual presentation of categorical data, with geom_bar() (height of the bar proportional to the number of cases in each group)

# Let's take a variable that we recoded as `factor`
class(autism_pids$ethnicity)
[1] "factor"

Barchart (cont.)

#### ...bare minimum ---------------------------------- 
autism_pids %>% 
  ggplot(aes(x = ethnicity )) + 
  geom_bar() +   
  theme_bw() 

…improve theme

autism_pids %>% 
  ggplot(aes(x = ethnicity )) + 
  geom_bar(fill = "steelblue") +
  # reference line  
  geom_hline(yintercept=100, color = "#9b2339", size=0.5, ) +
  labs(x = "ethnicity", y = "n of individuals",
       color = "Stats",
       title = "Distribution of observations by ethnicity",
       subtitle = "",
       caption = "Autism study")  +
  # --- wrap long x labels (flipped ) !!!
  #  scale_x_discrete(labels = function(x) stringr::str_wrap(x, width = 10)) +
  theme_bw() +
  theme(axis.text.x = element_text(angle=50, vjust=0.75), 
        axis.text.y = element_text(size=10,face="bold"))  

…improve theme

…improve readability (reorder)

Reordering the bars by count using the package forcats and its function fct_infreq + (which we can do because ethnicity is coded as factor)

autism_pids %>% 
    # we modify our x like so 
    ggplot(aes(x = forcats::fct_infreq(ethnicity ))) + 
    geom_bar(fill = "steelblue") +
    geom_hline(yintercept=100, color = "#9b2339", size=0.5, ) +
    labs(x = "ethnicity", y = "n of individuals",
         color = "Stats",
         title = "Distribution of observations by ethnicity",
         subtitle = "",
         caption = "Autism study")  +
    # --- wrap long x labels (flipped ) !!!
    #  scale_x_discrete(labels = function(x) stringr::str_wrap(x, width = 10)) +
    theme_bw() +
    theme(axis.text.x = element_text(angle=50, vjust=0.75), 
          axis.text.y = element_text(size=10,face="bold"))  

…improve readability (reorder)

…improve readability (highlight NA)

Let’s highlight the fact that the last column is the number of missing values.

# Highlight "NA" as separate category
autism_pids %>%
  ## --- prep the dataframe 
  # Add a factor variable with two levels to use as fill/highlight
  dplyr::mutate(highlight = forcats::fct_other(
    ethnicity, keep = "NA", other_level = "All Groups"))  %>% 
  ## --- ggplot 
  # we ADD to `aes mapping` also `fill = highlight`
  ggplot(aes(x = forcats::fct_infreq(ethnicity), fill = highlight)) + 
  geom_bar()+
  # Use custom color palettes
  scale_fill_manual(values=c("#0084e6")) +
  # Add a line at a significant level 
  geom_hline(yintercept=100, color = "#9b2339", size=0.5, ) +
  labs(x = "ethnicity", y = "n of individuals",
       color = "Stats",
       title = "Distribution of observations by ethnicity",
       subtitle = "",
       caption = "Autism study")  +
  # --- wrap long x labels (flipped ) !!!
  #  scale_x_discrete(labels = function(x) stringr::str_wrap(x, width = 10)) +
  theme_bw() +
  theme(axis.text.x = element_text(angle=50, vjust=0.75), 
        axis.text.y = element_text(size=10,face="bold"))  +
  ## drop legend and Y-axis title
  theme(legend.position = "none") 

…improve readability (highlight NA)

Boxplot

As discussed in lecture 1, the boxplot is packed with information about a distribution.

autism_pids %>% 
  ggplot(aes(x = gender,  y= age_inputed, fill = gender)) +
  geom_boxplot(alpha=0.5)+
  theme_bw()   + 
  scale_fill_cyclical(values = c("#9b2339","#005ca1"))

Boxplot

Violin plot

Similarly, the violin plot is an interesting alternative, and it can be enriched by adding the geom_point geometry.

autism_pids %>% 
  ggplot(mapping = aes(y = age_inputed, x = gender, fill = gender)) +
  geom_violin(alpha=0.5) +
  geom_point(position = position_jitter(width = 0.1), size = 0.5)+ 
  scale_fill_cyclical(values = c("#9b2339","#005ca1")) +
  theme_bw()

Violin plot

SAVING & EXPORTING OUTPUT ARTIFACTS

Saving one plot

If I want to use these output files later, I can easily save in the output folder created at the beginning.

ggsave (hist_plot, 
        filename = here::here("practice",  "data_output", "hist_plot.png"))

Saving a .Rds data file.

saveRDS (object = autism_pids, 
         file =  here::here("practice",  "data_output", "autism_pids_v2.Rds"))
# to load it later I will use 
readRDS(here::here("practice",  "data_output", "autism_pids_v2.Rds"))